package com.ai.web.weixin.processor;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.web.service.WxUserService;
import com.ai.web.vo.WxUserV;
import com.ai.web.weixin.message.request.ReqBaseMessage;
import com.ai.web.weixin.message.request.TextMessage;
import com.ai.web.weixin.message.util.MessageUtil;
import com.tiny.persistence.domain.WxUser;

@Service(value="textMsgProcessor")
public class TextMsgProcessor implements IMessageProcessor {

	private static Logger logger = Logger.getLogger(TextMsgProcessor.class);
	@Autowired
	private WxUserService wxUserService;
	
	public String process(ReqBaseMessage bm) {
		logger.info("[Text Processor] " + bm.toString());
		TextMessage tm = (TextMessage) bm;
		logger.info("[Text tm] " + tm.toString());
		String[] params = tm.getContent().split("#");
		logger.info("[Text params] " + params.length);
		if(params.length == 3){
			WxUser user = wxUserService.getByOpenId(bm.getFromUserName());
		    logger.info("[Text user] " + user);
			WxUserV userV = new WxUserV();
			if(user != null){
				BeanUtils.copyProperties(user, userV);
			}
			if(userV.getIsPassed() == 0){
				userV.setUsername(params[0]);
				userV.setMobilePhone(params[1]);
				userV.setCompany(params[2]);
			}else{
				userV.setIsPassed(0);
			}
			try {
				logger.info("[Text userV] " + userV.toString());
				wxUserService.saveWxUser(userV);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String content = "您好,您的信息已提交,审核通过后即可获取更多功能。";
			// 回复文本消息  
			com.ai.web.weixin.message.response.TextMessage textMessage = new com.ai.web.weixin.message.response.TextMessage();  
	        textMessage.setToUserName(bm.getFromUserName());  
	        textMessage.setFromUserName(bm.getToUserName());  
	        textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
	        textMessage.setContent(content);
			return MessageUtil.textMessageToXml(textMessage);
		}else{
			String content = "您好,您提交的信息格式不对，请回复如下格式：<a href=\"#\">\"姓名"
				+ "#手机号码#公司名称\"</a>";
			// 回复文本消息  
			com.ai.web.weixin.message.response.TextMessage textMessage = new com.ai.web.weixin.message.response.TextMessage();  
	        textMessage.setToUserName(bm.getFromUserName());  
	        textMessage.setFromUserName(bm.getToUserName());  
	        textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
	        textMessage.setContent(content);
			return MessageUtil.textMessageToXml(textMessage);
		}
	}

}
